import { FC, useCallback, useEffect, useState } from "react";
import {
  UploadFile,
  UploadProps,
  Upload as AtUpload,
  message,
} from "antd";
import type { RcFile } from "antd/es/upload";
import { CompProps } from "../../types/comp";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import request from "../../utils/request";
import { baseApi } from '../../../public/config.json'

type FileType = string;

type Props = {
  fileType?: FileType;
  value?: string;
  onChange?: (v: any) => void;
  validateData?: (data: any) => void;
  hideLoadingNative?: boolean,
  onLoading?: (bol: boolean) => void;
} & Omit<UploadProps, "onChange"> &
  CompProps;

const Upload: FC<Props> = ({
  onLoading,
  onChange,
  validateData,
  value,
  children,
  hideLoadingNative,
  ...uploadProps
}) => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [loading, setLoading] = useState(false);
  const onUploadChange: UploadProps["onChange"] = ({ file, fileList }) => {
    const noHandleStatus = ["removed", "error"]
    if (hideLoadingNative) {
      noHandleStatus.push('uploading')
    }
    if (noHandleStatus.includes(file.status)) {
      onChange?.("");
    } else {
      setFileList(fileList);
    }
  };
  useEffect(() => {
    if (!value) {
      setFileList([]);
    } else {
      setFileList([
        {
          uid: "1",
          name: value,
          status: "done",
          url: value,
        },
      ]);
    }
  }, [value]);
  const onPreview = async (file: UploadFile) => {
    let src = file.url as string;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj as RcFile);
        reader.onload = () => resolve(reader.result as string);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  const isMax = uploadProps.maxCount
    ? uploadProps.maxCount <= fileList.length
    : false;
  const customRequest = useCallback(
    async (options: any) => {
      const formData = new FormData();
      formData.append("file", options.file);
      onLoading?.(true);
      setLoading(true);
      const data = await request
        .post("/hyqz/uploadFile", formData)
        .finally(() => {
          onLoading?.(false);
        });
      try {
        await validateData?.(data);
        onChange?.(data);
      } catch (e) {
        options.onError(e);
        setTimeout(() => {
          setFileList([]);
        });
      } finally {
        setLoading(false);
      }
    },
    [onChange, validateData]
  );



  return (
    <AtUpload
      action={baseApi + "/hyqz/uploadFile"}
      customRequest={customRequest}
      {...uploadProps}
      beforeUpload={(file) => {
        const isLt1G = file.size / 1024 / 1024 / 1024 < 1;
        if (!isLt1G) {
          message.error("文件大小请限制在1G内").then();
        }
        return isLt1G;
      }}
      onPreview={onPreview}
      onChange={onUploadChange}
      fileList={fileList}
      multiple={false}
    >
      {hideLoadingNative && loading ? 'Loading...' : (isMax ? null : (children || uploadButton))}
    </AtUpload>
  );
};

export default Upload;
